package com.hopu.service.impl;

import com.hopu.context.BaseContext;
import com.hopu.entity.Interaction;
import com.hopu.entity.Video;
import com.hopu.entity.WorkLikeDTO;
import com.hopu.mapper.VideoMapper;
import com.hopu.mapper.interactionMapper;
import com.hopu.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private interactionMapper interactionMapper;

    /**
     * 点赞/取消点赞
     * @param workLikeDTO
     */
    @Transactional
    @Override
    public void toggleLike(WorkLikeDTO workLikeDTO) {

        //获取当前用户id
        Integer userId = BaseContext.getCurrentId();

        //判断是否有记录,用户视频关系表
        Interaction interaction = interactionMapper.getByUserIdAndInteractionId(userId, workLikeDTO.getWorkId());

        //没记录
        if (interaction == null) {
            //封装数据
            Interaction inter = new Interaction();
            inter.setUserId(userId);
            inter.setWorkId(workLikeDTO.getWorkId());
            //设置点赞状态为1
            Short likeStatus = 1;
            inter.setLikeStatus(likeStatus);
            //插入数据
            interactionMapper.insert(inter);
            //点赞数加1
            videoMapper.incrementLikeCount(workLikeDTO);
        }else {
            //有记录,获取点赞状态
            Short currentStatus = interaction.getLikeStatus();
            if (currentStatus==null){
                currentStatus=Short.valueOf("0");
            }
            if (currentStatus == 1) {
                //以点赞,取消点赞
                Short toggleLikeStatus = 0;
                interaction.setLikeStatus(toggleLikeStatus);
                //更新点赞状态
                interactionMapper.updateLikeStatus(interaction);
                //点赞数减1
                videoMapper.decrementLikeCount(workLikeDTO);
            }else {
                //未点赞,重新点赞
                Short toggleLikeStatus = 1;
                interaction.setLikeStatus(toggleLikeStatus);
                //更新点赞状态
                interactionMapper.updateLikeStatus(interaction);
                //点赞数加1
                videoMapper.incrementLikeCount(workLikeDTO);
            }
        }

    }

    /**
     * 查询点赞数
     * @param video
     * @return
     */
    @Override
    public Integer getLikeCount(Video video) {
        Integer workId = video.getWorkId();
        return videoMapper.getLikeCount(workId);
    }
}
